package com.zxl.readsms

import android.Manifest
import android.content.*
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.text.TextUtils.SimpleStringSplitter
import android.text.method.ScrollingMovementMethod
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.permissionx.guolindev.PermissionX
import com.pgyer.pgyersdk.PgyerSDKManager
import com.pgyer.pgyersdk.callback.CheckoutCallBack
import com.pgyer.pgyersdk.model.CheckSoftModel
import java.util.*

class SmsAct : AppCompatActivity() {
    private lateinit var sp:SharedPreferences
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        sp=getSharedPreferences(SP_NAME,MODE_PRIVATE)
        val textView = findViewById<TextView>(R.id.notice)
        textView.movementMethod = ScrollingMovementMethod.getInstance()
        val type= sp.getInt("PUSH_TYPE",2)
        findViewById<Button>(R.id.btn_add_mail).visibility=if (type==2) View.VISIBLE else View.GONE
        //动态申请权限
        checkPermission()
        findViewById<Button>(R.id.btn_setting).setOnLongClickListener {
            val pushType = if (PUSH_TYPE == 1) {
                PUSH_TYPE = 2
                "邮件"
            } else {
                PUSH_TYPE = 1
                "微信"
            }
            val edit=sp.edit()
            edit.putInt("PUSH_TYPE",PUSH_TYPE)
            edit.commit()
            val type= sp.getInt("PUSH_TYPE",1)
            Log.e("zxl", "type====$type")
            Toast.makeText(this@SmsAct, "切换为${pushType}推送", Toast.LENGTH_SHORT).show()
            findViewById<Button>(R.id.btn_add_mail).visibility=if (PUSH_TYPE==2) View.VISIBLE else View.GONE
            true
        }
        findViewById<Button>(R.id.btn_auto_start).setOnLongClickListener {
            if (PUSH_TYPE == 1) {
                PUSH_TO_WX_TOPIC=!PUSH_TO_WX_TOPIC
                sp.edit().putBoolean("PUSH_TO_WX_TOPIC",PUSH_TO_WX_TOPIC)
                sp.edit().apply()
                Toast.makeText(this@SmsAct, "${if (PUSH_TO_WX_TOPIC) "开启" else "关闭" }推给所有关注用户", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this@SmsAct, "请先切换到微信推送模式", Toast.LENGTH_SHORT).show()
            }
            true
        }
    }

    private fun checkPermission() {
        PermissionX.init(this)
            .permissions(Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS,Manifest.permission.READ_PHONE_STATE,Manifest.permission.READ_PHONE_NUMBERS)
            .request { allGranted, _, _ ->
                if (allGranted) {
                    Log.e("zxl", "所有权限都通过")

                } else {
                    Toast.makeText(this, "请同意所有权限", Toast.LENGTH_LONG).show()
                    checkPermission()
                }
            }
    }

    private fun isAccessibilitySettingsOn(mContext: Context): Boolean {
        var accessibilityEnabled = 0
        val service = packageName + "/" + DemoService::class.java.canonicalName
        try {
            accessibilityEnabled = Settings.Secure.getInt(
                mContext.applicationContext.contentResolver,
                Settings.Secure.ACCESSIBILITY_ENABLED
            )
        } catch (e: Settings.SettingNotFoundException) {
            e.printStackTrace()
        }
        val mStringColonSplitter = SimpleStringSplitter(':')
        if (accessibilityEnabled == 1) {
            val settingValue: String = Settings.Secure.getString(
                mContext.applicationContext.contentResolver,
                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
            )
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue)
                while (mStringColonSplitter.hasNext()) {
                    val accessibilityService = mStringColonSplitter.next()
                    if (accessibilityService.equals(service, ignoreCase = true)) {
                        return true
                    }
                }
            }
        }
        return false
    }

    override fun onResume() {
        super.onResume()
        val btnAsb=findViewById<Button>(R.id.btn_assb)
        if (isAccessibilitySettingsOn(this)){
            btnAsb.isEnabled=false
            btnAsb.text="已开启"
        }else{
            btnAsb.isEnabled=true
            btnAsb.text="去开启无障碍"
        }
        PgyerSDKManager.checkVersionUpdate(this, object : CheckoutCallBack {
            override fun onNewVersionExist(model: CheckSoftModel) {
                //检查版本成功（有新版本）
                val bb=AlertDialog.Builder(this@SmsAct)
                    .setTitle("新版本${model.buildVersion}")
                    .setMessage(model.buildUpdateDescription?:"暂无更新说明")
                    .setCancelable(false)
                    .setPositiveButton("去下载"
                    ) { p0, _ ->
                        p0.dismiss()
                        val intent=Intent(Intent.ACTION_VIEW)
                        val uri = Uri.parse(model.buildShortcutUrl)
                        intent.data = uri
                        this@SmsAct.startActivity(intent)
                    }
                    .setNegativeButton("取消",null)
                    .create()
                bb.show()
            }

            override fun onNonentityVersionExist(error: String) {
                //无新版本
            }

            override fun onFail(error: String) {
                //请求异常
            }
        })
    }
    fun openAccessible(view: View) {
        val intent =  Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
        startActivity(intent)
    }

    private fun getAutostartSettingIntent(context: Context): Intent {
        var componentName: ComponentName? = null
        val brand = Build.MANUFACTURER
        val intent = Intent()
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        when (brand.lowercase(Locale.getDefault())) {
            "samsung" -> componentName = ComponentName(
                "com.samsung.android.sm",
                "com.samsung.android.sm.app.dashboard.SmartManagerDashBoardActivity"
            )
            "huawei" ->
                //荣耀V8，EMUI 8.0.0，Android 8.0上，以下两者效果一样
                componentName = ComponentName(
                    "com.huawei.systemmanager",
                    "com.huawei.systemmanager.mainscreen.MainScreenActivity"
                )
            "xiaomi" -> componentName = ComponentName(
                "com.miui.securitycenter",
                "com.miui.permcenter.autostart.AutoStartManagementActivity"
            )
            "vivo" ->
                // componentName = new ComponentName("com.iqoo.secure", "com.iqoo.secure.safaguard.PurviewTabActivity");
                componentName = ComponentName(
                    "com.iqoo.secure",
                    "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity"
                )
            "oppo" ->
                // componentName = new ComponentName("com.oppo.safe", "com.oppo.safe.permission.startup.StartupAppListActivity");
                componentName = ComponentName(
                    "com.coloros.oppoguardelf",
                    "com.coloros.powermanager.fuelgaue.PowerUsageModelActivity"
                )
            "yulong", "360" -> componentName = ComponentName(
                "com.yulong.android.coolsafe",
                "com.yulong.android.coolsafe.ui.activity.autorun.AutoRunListActivity"
            )
            "meizu" -> componentName =
                ComponentName("com.meizu.safe", "com.meizu.safe.permission.SmartBGActivity")
            "oneplus" -> componentName = ComponentName(
                "com.oneplus.security",
                "com.oneplus.security.chainlaunch.view.ChainLaunchAppListActivity"
            )
            "letv" -> {
                intent.action = "com.letv.android.permissionautoboot"
                intent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
                intent.data = Uri.fromParts("package", context.packageName, null)
            }
            else -> {
                intent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
                intent.data = Uri.fromParts("package", context.packageName, null)
            }
        }
        intent.component = componentName
        return intent
    }

    fun goAutoStart(view: View) {
        val intent =  getAutostartSettingIntent(this)
        startActivity(intent)
    }

    fun openAppSet(view: View) {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            .setData(Uri.fromParts("package", packageName, null))
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(intent)
    }

    fun addEmail(view: View) {
        startActivity(Intent(this,AddMailAct::class.java))
    }
}